﻿
using Microsoft.Extensions.DependencyInjection;
using Stee.CAP8.MessageBus.Interface.Interfaces;
using Stee.CAP8.MessageBus.Kafka.Publisher;
using Stee.CAP8.MessageBus.Kafka.Subscriber;
using Stee.CAP8.MessageBus.Sagas.Core.Sagas;
using Stee.CAP8.MessageBus.Sagas.Core.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace Stee.CAP8.MessageBus.Sagas.Core.Extensions
{
    public static class EventBusExtension
    {

        public static IServiceCollection UseKafkaEventStore(this IServiceCollection services)
        {

            services.AddSingleton(typeof(IBus), typeof(EventBus));
            services.AddTransient<IPublisher, PublisherImpl>();
            services.AddTransient<ISubscriber, SubscriberImpl>();
            services.AddSingleton(typeof(ISagaStorage), typeof(InMemorySagaStorage));

            return services;
        }

    


        public static IServiceCollection AddSaga(this IServiceCollection services)
        {
            var provider = services.BuildServiceProvider();
            var alltypes = Assembly.GetCallingAssembly().GetTypes();

            var typeHandle = typeof(BaseMainSaga<>);
            var implementSagaList = alltypes.Where(x => x.IsSubClassOfRawGeneric(typeHandle));


            implementSagaList.ToList().ForEach(type =>
            {
                services.AddSingleton(type);
                TypeStore.Insert(type);
                Console.WriteLine("注册成功" + type.FullName);

            });
            return services;

        }

        public static IServiceCollection AddSubSaga(this IServiceCollection services)
        {
            var provider = services.BuildServiceProvider();
            var alltypes = Assembly.GetCallingAssembly().GetTypes();
            //获取调用程序集当中所有实现了ISagaData的类,即用户自定义的sagaData

            var typeHandle = typeof(ISubSaga);
            var subSagaList = alltypes.Where(x => typeHandle.IsAssignableFrom(x));


            subSagaList.ToList().ForEach(type =>
            {
                services.AddSingleton(type);
                TypeStore.Insert(type);
                Console.WriteLine("注册成功" + type.FullName);

            });
            return services;

        }




     

        public static IServiceCollection UseEventBus(this IServiceCollection services, Action<IBus> busAction)
        {
            var provider = services.BuildServiceProvider();
            if (provider == null) throw new ArgumentNullException(nameof(provider));
            if (busAction == null) throw new ArgumentNullException(nameof(busAction));


            var bus = provider.GetService<IBus>();

            busAction(bus);

            return services;
        }



    }
}
